<template>
  <div class="realname-container">
    <div class="nav-bar">
      <button class="back" @click="$router.back()">‹</button>
      <div class="title">实名认证</div>
      <div class="right"></div>
    </div>

    <div class="form-card">
      <div class="form-title">实名认证</div>

      <!-- 上传身份证照片 -->
      <div class="upload-section">
        <div class="upload-item">
          <div class="upload-label">身份证人像面</div>
          <div class="upload-box" @click="selectImage('front')">
            <img v-if="form.frontImage" :src="form.frontImage" class="preview-image" />
            <div v-else class="upload-placeholder">
              <div class="upload-icon">📷</div>
              <div class="upload-text">点击上传</div>
            </div>
          </div>
          <input 
            ref="frontInput" 
            type="file" 
            accept="image/*" 
            @change="handleImageChange($event, 'front')" 
            style="display: none"
          />
        </div>

        <div class="upload-item">
          <div class="upload-label">身份证国徽面（选填）</div>
          <div class="upload-box" @click="selectImage('back')">
            <img v-if="form.backImage" :src="form.backImage" class="preview-image" />
            <div v-else class="upload-placeholder">
              <div class="upload-icon">📷</div>
              <div class="upload-text">点击上传</div>
            </div>
          </div>
          <input 
            ref="backInput" 
            type="file" 
            accept="image/*" 
            @change="handleImageChange($event, 'back')" 
            style="display: none"
          />
        </div>
      </div>

      <!-- OCR识别按钮 -->
      <button 
        v-if="form.frontImage && !form.name" 
        class="ocr-btn" 
        @click="recognizeIdCard"
        :disabled="recognizing"
      >
        {{ recognizing ? '识别中...' : '自动识别身份证信息' }}
      </button>

      <div class="form-item">
        <label for="realname-name">姓名</label>
        <input id="realname-name" name="name" v-model.trim="form.name" type="text" placeholder="姓名" />
      </div>

      <div class="form-item">
        <label for="realname-id">身份证号码</label>
        <input id="realname-id" name="idNumber" v-model.trim="form.idNumber" type="text" placeholder="身份证号码" />
      </div>

      <label class="agree">
        <input id="realname-agree" name="agree" type="checkbox" v-model="agreed" />
        <span>同意<span class="link" @click.prevent="openTerms">用户服务协议</span>和<span class="link" @click.prevent="openPrivacy">隐私政策条款</span></span>
      </label>

      <button class="submit" :disabled="!canSubmit" @click="handleSubmit">确定</button>
    </div>
  </div>
</template>

<script setup>
import { reactive, computed, ref } from 'vue'
import api from '@/api'

const form = reactive({
  name: '',
  idNumber: '',
  frontImage: null,  // 身份证正面预览
  backImage: null,   // 身份证背面预览
  frontImageBase64: null,  // 身份证正面 Base64
  backImageBase64: null    // 身份证背面 Base64
})

const agreed = ref(false)
const recognizing = ref(false)
const frontInput = ref(null)
const backInput = ref(null)

const canSubmit = computed(() => {
  const cleanId = (form.idNumber || '').replace(/\s/g, '')
  return agreed.value && form.name.trim().length >= 2 && validateId(cleanId)
})

function validateId(id) {
  // 简单校验：18位，末尾可为X/x
  return /^[0-9]{17}[0-9Xx]$/.test(id)
}

// 选择图片
function selectImage(side) {
  if (side === 'front') {
    frontInput.value?.click()
  } else {
    backInput.value?.click()
  }
}

// 处理图片选择
function handleImageChange(event, side) {
  const file = event.target.files?.[0]
  if (!file) return

  // 检查文件大小（限制5MB）
  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过5MB')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    const dataUrl = e.target.result
    if (side === 'front') {
      form.frontImage = dataUrl
      form.frontImageBase64 = dataUrl.split(',')[1]  // 去掉 data:image/...;base64, 前缀
    } else {
      form.backImage = dataUrl
      form.backImageBase64 = dataUrl.split(',')[1]
    }
  }
  reader.readAsDataURL(file)
}

// OCR识别身份证
async function recognizeIdCard() {
  if (!form.frontImageBase64) {
    alert('请先上传身份证人像面照片')
    return
  }

  recognizing.value = true
  try {
    const response = await api.post('/identity/ocr', {
      image_base64: form.frontImageBase64,
      id_card_side: 'front'
    })

    console.log('=== OCR识别完整结果 ===')
    console.log('完整响应:', response.data)
    console.log('data字段:', response.data.data)
    console.log('data字段类型:', typeof response.data.data)
    console.log('data字段内容:', JSON.stringify(response.data.data, null, 2))
    
    // 尝试从不同的字段路径提取数据
    console.log('尝试查找所有可能的字段:')
    console.log('response.data:', Object.keys(response.data))
    
    // 如果 data 为空，尝试直接从 response.data 中查找
    if (Object.keys(response.data.data || {}).length === 0) {
      console.log('data为空，尝试其他路径...')
      console.log('response.data.words_result:', response.data.words_result)
      console.log('response.data.extracted:', response.data.extracted)
    }

    if (response.data.code === 'success') {
      const ocrData = response.data.data
      
      console.log('提取的姓名:', ocrData.name)
      console.log('提取的身份证号:', ocrData.id_number)
      
      // 自动填充姓名和身份证号
      if (ocrData.name) {
        form.name = ocrData.name
        console.log('✅ 已填充姓名')
      } else {
        console.warn('⚠️ OCR结果中没有姓名字段')
      }
      
      if (ocrData.id_number) {
        form.idNumber = ocrData.id_number
        console.log('✅ 已填充身份证号')
      } else {
        console.warn('⚠️ OCR结果中没有身份证号字段')
      }

      if (ocrData.name || ocrData.id_number) {
        alert('身份证信息识别成功！')
      } else {
        alert('识别成功，但未提取到姓名和身份证号，请手动填写')
      }
    } else {
      alert('识别失败：' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('OCR识别失败:', error)
    console.error('错误响应数据:', error.response?.data)
    console.error('错误状态码:', error.response?.status)
    console.error('错误详情:', error.response?.data?.detail)
    
    const errorMsg = error.response?.data?.detail || '网络错误'
    
    // 如果是配额限制错误，提示用户可以手动填写
    if (errorMsg.includes('限制') || errorMsg.includes('用完')) {
      alert(`❌ ${errorMsg}\n\n💡 您可以手动填写姓名和身份证号，不影响提交`)
    } else {
      alert('识别失败：' + errorMsg)
    }
  } finally {
    recognizing.value = false
  }
}

async function handleSubmit() {
  const token = localStorage.getItem('token')
  
  if (!token || token === 'null' || token === 'undefined') {
    alert('请先登录后再进行实名认证')
    window.location.href = '/login'
    return
  }

  try {
    const requestData = {
      name: form.name,
      id_number: form.idNumber,
      front_image_base64: form.frontImageBase64,
      back_image_base64: form.backImageBase64
    }
    
    console.log('提交实名认证...')
    const response = await api.post('/identity/verify', requestData)
    console.log('提交成功:', response.data)
    
    alert('已提交实名认证信息，正在审核')
    history.back()
  } catch (e) {
    console.error('提交失败:', e)
    console.error('错误响应数据:', e.response?.data)
    console.error('错误状态码:', e.response?.status)
    console.error('错误详情:', e.response?.data?.detail)
    
    if (e.response?.status === 401) {
      const errorDetail = e.response?.data?.detail || '登录已过期'
      alert(`认证失败：${errorDetail}\n请重新登录后再试`)
      localStorage.clear()
      window.location.href = '/login'
      return
    }
    
    const errorDetail = e?.response?.data?.detail || '提交失败，请稍后重试'
    alert('❌ ' + errorDetail)
  }
}

function openTerms() {
  alert('用户服务协议（示意）')
}

function openPrivacy() {
  alert('隐私政策条款（示意）')
}
</script>

<style scoped>
.realname-container {
  min-height: 100vh;
  background: #f7f8fa;
}

.nav-bar {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px;
  border-bottom: 1px solid #eee;
  background: #fff;
}

.back {
  border: none;
  background: none;
  font-size: 22px;
}

.title {
  font-size: 16px;
  font-weight: 600;
}

.form-card {
  margin: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.03);
}

.form-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-bottom: 14px;
}

.form-item label { color: #666; font-size: 13px; }

.form-item input {
  height: 40px;
  padding: 0 12px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  outline: none;
}

.agree {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 13px;
  margin: 8px 0 16px;
}

.link { color: #1677ff; cursor: pointer; }

.submit {
  width: 100%;
  height: 44px;
  border: none;
  border-radius: 8px;
  background: #5b8cff;
  color: #fff;
  font-size: 16px;
}

.submit:disabled {
  background: #c6d4ff;
}

.upload-section {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.upload-item {
  flex: 1;
}

.upload-label {
  color: #666;
  font-size: 13px;
  margin-bottom: 8px;
}

.upload-box {
  width: 100%;
  height: 140px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-box:hover {
  border-color: #5b8cff;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.upload-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 13px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.ocr-btn {
  width: 100%;
  height: 40px;
  margin-bottom: 16px;
  border: 1px solid #5b8cff;
  border-radius: 8px;
  background: #fff;
  color: #5b8cff;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.ocr-btn:hover:not(:disabled) {
  background: #f0f5ff;
}

.ocr-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
